<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace app\web\controller;
use app\src\weixin\logic\WeixinLogic;
use app\src\weixin\logic\Wechat;
use \xsocketlog\socketlog;
/*
 * 微信通信控制器
 */
class Weixin extends Base {

	const MSG_TYPE_TEXT = 'text';
	const MSG_TYPE_IMAGE = 'image';
	const MSG_TYPE_VOICE = 'voice';
	const MSG_TYPE_VIDEO = 'video';
	const MSG_TYPE_MUSIC = 'music';
	const MSG_TYPE_NEWS = 'news';
	const MSG_TYPE_LOCATION = 'location';
	const MSG_TYPE_LINK = 'link';
	const MSG_TYPE_EVENT = 'event';
    //微信默认返回
    const DEFAULT_REPLY = "";

	//TOKEN ，通信地址参数，非微信接口配置中的token
    protected $token;
	//通信消息主体
	public $data = array();
	//通信的粉丝的可获取的信息
	public $fans;
	//当前通信的公众号信息
	public $wxaccount;

    protected $userinfo;
    protected $memberinfo;

    protected $wxapi;
	
	private function getPluginParams(){
		return array("fans"=>$this->fans,"data"=>$this->data,"wxaccount"=>$this->wxaccount);
	}
	
	protected function _initialize() {
		parent::_initialize();
            $account=['id'=>1,
                'appid'=>'wx8ec96a74711b3fb0',
                'appsecret'=>'1b08bfa933d0280736f833dee23dbd68',
                'encodingaeskey'=>'jJBvCe8JhwTkuXMHJvZI73hu46LeVofXnrK0vVCJSCY',
                'token'=>'ycyb'];
            $result=['status'=>true,'info'=>$account];
            $this -> token=$account['token'];
            if ($result['status']) {
                $this -> wxaccount = $result['info'];
            }
            cache('weixin_' . $this -> token, $this -> wxaccount, 600);
        $this->wxapi=new WeixinLogic($this -> wxaccount['appid'], $this -> wxaccount['appsecret']);

//        if (session("?global_user")) {
//            $this->userinfo = session("global_user");
//        }else{
//            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//            $this->getWxuser($url);
//        }
	}	
	// zyh openid= orQY30Q0_dlv3rMzml93BNunUdPU
	public function index() {
		if (!class_exists('SimpleXMLElement')) {
			exit('SimpleXMLElement class not exist');
		}
		if (!function_exists('dom_import_simplexml')) {
			exit('dom_import_simplexml function not exist');
		}
//        $socketlog = new socketlog('hdg');
//        $hhh= simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']);
//        $socketlog->send($hhh);
		$weixin = new Wechat($this -> token, $this -> wxaccount['encodingaeskey'], $this -> wxaccount['appid']);
			$this -> data = $weixin -> request();
        if ($this -> data && is_array($this -> data)) {
        //    $fanskey = $this->getOpenID();
            //读取缓存的粉丝信息
      //      $this -> fans = ;
//            $contentStr='ces';
//            $resultStr = $this->response_text($this -> data,$contentStr);
//            echo $resultStr;
      //      dump('xx');exit;
            $reply = $this -> reply();
            if(empty($reply)){
                exit("success");
            }
            list($content, $type) = $reply;

            $weixin -> response($content, $type);
        } else {
            $weixin -> response("我不知道你讲的是什么意思 : )", self::MSG_TYPE_TEXT);
        }
	}


    //响应
    private function reply() {

        $weixin = new Wechat($this -> token, $this -> wxaccount['encodingaeskey'], $this -> wxaccount['appid']);
        //转化为小写
     //  dump('xx');exit;
        if(!empty($this -> data['Event'])) {
            $this->data['Event'] = strtolower($this->data['Event']);
        }
        $this -> data['MsgType'] = strtolower($this -> data['MsgType']);
    //    dump($this -> data['MsgType']);exit;
//        if($this->data['Event']  != $weixin::MSG_EVENT_LOCATION){
//            addWeixinLog($this->data,"【来自微信服务器消息】");
//        }
//
//        $return = self::DEFAULT_REPLY;

        //=====================微信事件转化为系统内部可处理
        if ($this -> data['MsgType'] == self::MSG_TYPE_EVENT) {
            //接收事件推送

       //    dump('xx');exit;
            switch ($this->data['Event']) {

                case $weixin::MSG_EVENT_CLICK :
                    $return = $this -> menuClick();
                    break;
                case $weixin::MSG_EVENT_VIEW :
                    $return = $this -> menuView();
                    break;
                case $weixin::MSG_EVENT_SCAN :
                    $return = $this -> qrsceneScan();
                    break;
                case $weixin::MSG_EVENT_MASSSENDJOBFINISH :
                    //群发任务结束
                    break;
                case $weixin::MSG_EVENT_SUBSCRIBE :
                    $return = $this -> subscribe();
                    break;
                case $weixin::MSG_EVENT_UNSUBSCRIBE :
                    $return = $this -> unsubscribe();
                    break;
                case $weixin::MSG_EVENT_LOCATION :
                    //用户自动上报地理位置
                    $return = $this -> locationProcess();
                    break;
                default :
                    break;
            }
        } else {
            //接受普通消息
            switch ($this->data['MsgType']) {

                case self::MSG_TYPE_TEXT :
                    $return = $this -> textProcess();
                    break;
                case self::MSG_TYPE_IMAGE :
                    $return = $this -> imageProcess();
                    break;
                case self::MSG_TYPE_VIDEO :
                    $return = $this -> videoProcess();
                    break;
                case self::MSG_TYPE_LOCATION :
                    //用户手动发送地理位置
                    $return = $this -> locationProcess();
                    //群发任务结束
                    break;
                case self::MSG_TYPE_LINK :
                    break;
                case self::MSG_TYPE_VOICE :
                    $return = $this -> voiceProcess();
                    break;
                default :
                    break;
            }
        }

        //=====================系统内置其它方法响应微信处理
      //  dump($return);exit;
        if(empty($return)){
            //只在上面的处理方法，无法处理时才进行下面处理
            $return = $this->innerProcess();
        }

        return $return;
    }

    //END reply

    private $Plugins = array(
        '_promotioncode_'=>"Promotioncode",
    );

    /**
     * 处理用户发送的视频消息
     */
    private function videoProcess() {
        return self::DEFAULT_REPLY;
    }
    private function innerProcess(){

        addWeixinLog($this->data,"innerProcess");
//        return array($this -> getOpenID(), self::MSG_TYPE_TEXT);
        //系统内置关键词处理方式
        //统一以包括上_
        switch (strtolower($this->data['Content'])) {
            case 'id' :
                // 当前粉丝的openid
                $return = array($this -> getOpenID(), self::MSG_TYPE_TEXT);
                break;
//			case '_promotioncode_':
//				//TODO: 考虑从数据库中取得 关键词对应的插件标识名
//				addWeixinLog($this->getPluginParams(),"[Promotioncode]");
//				$return = pluginCall($this->Plugins['_promotioncode_'],array($this->getPluginParams()));
//
//				$return = pluginCall("Promotioncode",array($this->getPluginParams()));
//				break;
            default :
                $return = pluginCall("Unknown",array($this->getPluginParams()));
                //TODO: 可以检测用户请求数
                break;
        }

        return $return;
    }


    /**
     * 处理用户发送的文本消息
     */
    private function textProcess($keyword='') {
        if(empty($keyword)){
            $keyword = $this->data['Content'];
        }


        $map = array('keyword'=>$keyword);

        return array('欢迎关注有车有保' , self::MSG_TYPE_TEXT);
        $result = apiCall(WxreplyTextApi::GET_INFO,array($map));


        if($result['status'] && !is_null($result['info'])){
            $siteurl = C("SITE_URL");
            //多图文
            $newslist = array();
            foreach($result['info'] as $key=>$news){
                array_push($newslist,array($news['title'],$news['description'],$siteurl.getPictureURL($news['piclocal'],$news['picremote']),$news['url']));
            }
            return array($newslist , self::MSG_TYPE_NEWS);
        }

        return self::DEFAULT_REPLY;
    }

    /**
     * 处理用户发送的图片消息
     */
    private function imageProcess() {
        $keyword = $this->data['Content'];

        return self::DEFAULT_REPLY;
    }

    /**
     * 处理用户发送的语音消息
     */
    private function voiceProcess() {
        $this -> data['Content'] = $this -> data['Recognition'];
        return self::DEFAULT_REPLY;
    }

    /**
     * 地理位置上报处理
     */
    private function locationProcess() {
        //ToUserName	开发者微信号
        //FromUserName	发送方帐号（一个OpenID）
        //CreateTime	消息创建时间 （整型）
        //MsgType	消息类型，event
        //Event	事件类型，LOCATION
        //Latitude	地理位置纬度
        //Longitude	地理位置经度
        //Precision	地理位置精度

        //TODO: 地理位置上报处理
        //Latitude:30.313025
        //Longitude:120.366547
        //Precision:65.000000
        $lat = $this->data['Latitude'];
        $lng = $this->data['Longitude'];

        $uid = $this->fans['id'];
        $entity = array('lat'=>$lat,'lng'=>$lng,'loc_update_time'=>time());
        $result = apiCall(WxuserApi::SAVE_BY_ID,array($uid,$entity));


        return self::DEFAULT_REPLY;

    }

    //========================微信事件处理方法

    /**
     * 自定义菜单事件
     *  ToUserName	开发者微信号
    FromUserName	发送方帐号（一个OpenID）
    CreateTime	消息创建时间 （整型）
    MsgType	消息类型，event
    Event	事件类型，CLICK
    EventKey	事件KEY值，与自定义菜单接口中KEY值对应
     */
    private function menuClick() {
        //点击菜单拉取消息时的事件推送
        return array($this->data['EventKey'],self::MSG_TYPE_TEXT);

        $this->data['Content'] = $this->data['EventKey'];

    //    addWeixinLog($this->data['Content'],"menuClick");
        if(empty($return)){

        }
        return $return;

    }

    /**
     * 自定义菜单事件
     *  ToUserName	开发者微信号
    FromUserName	发送方帐号（一个OpenID）
    CreateTime	消息创建时间 （整型）
    MsgType	消息类型，event
    Event	事件类型，VIEW
    EventKey	事件KEY值，设置的跳转URL
     */
    private function menuView() {
        //点击菜单跳转链接时的事件推送
        //TODO：统计自定义菜单的点击次数
        return "";
    }

    /**
     * 处理二维码扫描事件
     */
    private function qrsceneProcess($eventKey) {
        return array($this->data['FromUserName'] , self::MSG_TYPE_TEXT);
//        $addWxuserflag = false;
//        //$eventKey
//        //TODO: 处理二维码扫描事件
//        //TODO: 转到插件中处理
//        //如果是未关注用户扫码关注
//
//
//
//        if(strlen($eventKey)< 30){
//            $eventKey = intval(str_replace('UID_', '', $eventKey));
//            if (is_int($eventKey) && $eventKey > 0) {
//                $addWxuserflag = true;
//                $map['invite_code'] = $eventKey;
//                $invite_wxid = apiCall(WxuserApi::GET_INFO,array($map));
//                if($invite_wxid['status']) {
//                    $addWxuserflag = true;
//                    $wxid          = $invite_wxid['info']['id'];
////$add_test=apiCall(WxreplyTextApi::ADD,array(['keyword'=>33,'content'=>$wxid]));//推送测试
//
//                    $this->addWxuser($eventKey,'',$wxid);
//                }
//            }
//
//        }
//        //如果是已关注用户，再次扫码
//        //if(is_numeric($eventKey)){
//        if(strlen($eventKey)>30){
//
//            $map['invite_code'] = $eventKey;
//            $invite_wxid = apiCall(WxuserApi::GET_INFO,array($map));
//            if($invite_wxid['status']){
//
//                $addWxuserflag = true;
//                $wxid = $invite_wxid['info']['id'];
//                $this->addWxuser('0','0',$wxid);
//            }
//            addWeixinLog("用户uid= " . $eventKey, "【微信消息】");
//        }
//
//        if(!$addWxuserflag){
//
//            $this->addWxuser();
//        }
//        echo json_encode('',JSON_UNESCAPED_UNICODE);
//        return "";

    }

    /**
     * 关注事件
     */
    private function subscribe() {
//        if (isset($this -> data['EventKey']) && !empty($this->data['EventKey'])) {
//            //TODO: 处理用户通过推广二维码进行关注的事件
//            $eventKey = $this -> data['EventKey'];
//
//
//            $this -> qrsceneProcess(str_replace("qrscene_", "", $eventKey));
//
//
//        } else {
            //扫描公众号二维码进行关注
            return array('欢迎关注有车有保' , self::MSG_TYPE_TEXT);
            $this->addWxuser();
     //   }

        $ss_keyword = C("SS_KEYWORD");
        if(!empty($ss_keyword)){
            return $this->textProcess($ss_keyword);//处理关键词
        }
        return "";
    }

    /**
     * 取消关注
     */
    private function unsubscribe() {
        //TODO: 取消关注
        //==更新粉丝为未关注
        $wxuser = array('subscribed' => 0);
        $result = apiCall(WxuserApi::SAVE, array( array('openid' => $this -> getOpenID(),'wxaccount'=>$this->wxaccount['id']), $wxuser));
        if (!$result['status']) {
            LogRecord($result['info'], __FILE__);
        }
        addWeixinLog("[unsubscribe]" . $this -> getOpenID(), "取消关注消息");
        return "";
    }

    /**
     * 用户已二维码扫描关注事件
     */
    private function qrsceneScan() {
        $eventKey = $this -> data['EventKey'];
        return $this -> qrsceneProcess($eventKey);
    }



    private function getDebugUser() {
        $this->userinfo = array(
            'id'           => 10,
            'uid'          => 236,
            'openid'       => 'oJz-Ks7mwh0CadiADLlAWfjE7vvw',
            'nickname'     => '老胖子何必都',
            'avatar'       => 'http://wx.qlogo.cn/mmopen/An6TFzHNImPecEhl1R3UWd26LlC1mvVgyhdh2KGCOb0yjQ4JNQnOicG2ysaKojzusSO9R3RE55Exq0lYKpVr3RRArU0u7kgjR/0',
            'score'        => 0,
            'wxaccount_id' => 5,
            'exp'          => 100,
            'groupid'      => 11,
            'subscribed'   => 1,
        );

        $this->openid = "oJz-Ks7mwh0CadiADLlAWfjE7vvw";
    }

    public function getWxuser($url) {
        $this->userinfo = null;
        //判断用户是否已经登录

        if (session("?global_user")) {
            $this->userinfo = session("global_user");//这里读入的是数组？
            $this->openid   = $this->userinfo['openid'];
        }

        if (!is_array($this->userinfo)) {
            $code  = input('get.code', '');
            $state = input('get.state', '');
            if (empty($code) && empty($state)) {
                $redirect = $this->wxapi->getOAuth2BaseURL($url, 'HomeIndexOpenid');
                $this->redirect($redirect);
            }
            if ($state == 'HomeIndexOpenid') {
                $accessToken  = $this->wxapi->getOAuth2AccessToken($code);
                $this->openid = $accessToken['openid'];
                $this->userinfo       = $this->wxapi->webGetUserInfo($accessToken['openid'], $accessToken['access_token']);
                session("global_user",$this->userinfo);
            }
        }
    }


    public function sendXF($openid,$price,$seller_name){
        $time=date('Y-m-d H:i:s', time());
        $data=array(
            "touser"=>"$openid",
            "template_id"=>"-zWL8eGDFaGT2g_DfZc1eP_7mk-pj7NNm2NMASUpL_o",
            "data"=>array(
                "first"=>array("value"=>"获得佣金！","color"=>"#173177"),
                "keyword1"=>array("value"=>$seller_name,"color"=>"#173177"),
                "keyword2"=>array("value"=>$price,"color"=>"#173177"),
                "keyword3"=>array("value"=>$time,"color"=>"#173177"),
                "remark"=>array("value"=>"您可以回复文字或语音对该商品及商家进行评价哦~","color"=>"#173177")
            ),

        );
       $res= $this->wxapi->sendTmplMsgToFans($data);
    }

    public function sendFX($openid){
        $data=array(
            "touser"=>"$openid",
            "template_id"=>"GD7EQ6mZtc8HrhjzIeDVPIsK-17yBpFSeFEO-fzxfEc",
            "data"=>array(
                "first"=>array("value"=>"获得佣金！","color"=>"#173177"),
                "keyword1"=>array("value"=>"10元","color"=>"#173177"),
                "keyword2"=>array("value"=>"2017-6-7","color"=>"#173177"),
                "remark"=>array("value"=>"请进入店铺查看详情！","color"=>"#173177")
            ),

        );
        $res= $this->wxapi->sendTmplMsgToFans($data);
    }
    public function sendYJ($openid,$money){
        $time=date('Y-m-d H:i:s', time());
        $data=array(
            "touser"=>"$openid",
            "template_id"=>"faYw-64BYvb-2qG6e4EZ41EovJZ4VJ35eA5ymMW7UxY",
            "data"=>array(
                "first"=>array("value"=>"获得佣金！","color"=>"#173177"),
                "keyword1"=>array("value"=>$money."元","color"=>"#173177"),
                "keyword2"=>array("value"=>"$time","color"=>"#173177"),
                "remark"=>array("value"=>"请进入店铺查看详情！","color"=>"#173177")
            ),

        );
        $res= $this->wxapi->sendTmplMsgToFans($data);
    }
public function createMenu(){
    $data=array(
        array('type'=>'view','name'=>'进入网站','key'=>'tc11152','url'=>SITE_URL.'/web.php/index/index'),
	  	);
    $res= $this->wxapi->createMenu($data);
  //  dump($res);

}

	/*
	 * 获取openid
	 */
	private function getOpenID() {
		return $this -> data['FromUserName'];
	}

}
